<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';

// 获取入住/退住申请列表
const fetchCheckInOutRequests = (params) => {
    // 过滤无效参数
    const filteredParams = Object.fromEntries(
        Object.entries(params).filter(([_, value]) => value !== '' && value !== null && value !== undefined)
    );
    return request.get('/residence/check-in-out-requests', { params: filteredParams });
};

// 提交入住/退住申请
const submitCheckInOutRequest = (data) => {
    return request.post('/residence/check-in-out-requests', data);
};

// 审核入住/退住申请
const reviewCheckInOutRequest = (id, data) => {
    return request.put(`/residence/check-in-out-requests/${id}/review`, data);
};

// 响应式数据
const requestList = ref([]);
const loading = ref(false);
const pagination = ref({
    page: 1,
    size: 10,
    total: 0,
});
const filterParams = ref({
    requestType: '',
    status: '',
});
const dialogVisible = ref(false);
const reviewDialogVisible = ref(false);
const form = ref({
    elderlyUserId: '',
    requestType: '',
});
const reviewForm = ref({
    approvedByAdminId: '',
    bedId: '',
    notes: '',
    status: '',
});
const rules = {
    elderlyUserId: [{ required: true, message: '请输入老人用户ID', trigger: 'blur' }],
    requestType: [{ required: true, message: '请选择申请类型', trigger: 'change' }],
};
const reviewRules = {
    approvedByAdminId: [{ required: true, message: '请输入审核管理员ID', trigger: 'blur' }],
    status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
    bedId: [
        {
            validator: (rule, value, callback) => {
                if (reviewForm.value.status === 'APPROVED' && currentReviewRequestType.value === 'check_in' && !value) {
                    callback(new Error('入住申请通过时必须填写床位ID'));
                }
                callback();
            },
            trigger: 'blur',
        },
    ],
};

// 申请类型和状态选项
const requestTypeOptions = ref([
    { label: '入住', value: 'CHECK_IN' },
    { label: '退住', value: 'CHECK_OUT' },
]);
const requestTypeOptions2 = ref([
    { label: '入住', value: 'check_in' },
    { label: '退住', value: 'check_out' },
]);
const statusOptions = ref([
    { label: '待审核', value: 'pending' },
    { label: '已通过', value: 'approved' },
    { label: '已拒绝', value: 'rejected' },
]);
const statusOptions2 = ref([
    { label: '待审核', value: 'PENDING' },
    { label: '已通过', value: 'APPROVED' },
    { label: '已拒绝', value: 'REJECTED' },
]);

// 当前审核的申请
const currentReviewRequestId = ref(null);
const currentReviewRequestType = ref('');

// 获取申请列表
const loadRequests = async () => {
    loading.value = true;
    try {
        const response = await fetchCheckInOutRequests({
            page: pagination.value.page,
            size: pagination.value.size,
            ...filterParams.value,
        });
        requestList.value = response.list;
        pagination.value.total = response.total;
    } catch (error) {
        const message = error.response?.data?.msg || '获取申请列表失败';
        ElMessage.error(message);
    } finally {
        loading.value = false;
    }
};

// 提交申请
const handleSubmit = async () => {
    try {
        await submitCheckInOutRequest(form.value);
        ElMessage.success('申请提交成功');
        dialogVisible.value = false;
        form.value = { elderlyUserId: '', requestType: '' };
        loadRequests();
    } catch (error) {
        const message = error.response?.data?.msg || '提交申请失败';
        ElMessage.error(message);
    }
};

// 打开提交申请弹窗
const openDialog = () => {
    dialogVisible.value = true;
};

// 打开审核弹窗
const openReviewDialog = (row) => {
    currentReviewRequestId.value = row.id;
    currentReviewRequestType.value = row.requestType.toLowerCase();
    reviewForm.value = {
        approvedByAdminId: '',
        bedId: '',
        notes: '',
        status: '',
    };
    reviewDialogVisible.value = true;
};

// 提交审核
const handleReviewSubmit = async () => {
    try {
        await reviewCheckInOutRequest(currentReviewRequestId.value, reviewForm.value);
        ElMessage.success('审核提交成功');
        reviewDialogVisible.value = false;
        reviewForm.value = { approvedByAdminId: '', bedId: '', notes: '', status: '' };
        loadRequests();
    } catch (error) {
        const message = error.response?.data?.msg || '审核提交失败';
        ElMessage.error(message);
    }
};

// 分页处理
const handlePageChange = (page) => {
    if (!Number.isInteger(page) || page < 1) {
        ElMessage.error('无效的页码');
        pagination.value.page = 1;
        return;
    }
    pagination.value.page = page;
    loadRequests();
};

// 筛选处理
const handleFilter = () => {
    // 验证 page
    if (!Number.isInteger(pagination.value.page) || pagination.value.page < 1) {
        ElMessage.error('页码必须是正整数');
        pagination.value.page = 1;
    }
    // 验证 size
    if (!Number.isInteger(pagination.value.size) || pagination.value.size < 1 || pagination.value.size > 100) {
        ElMessage.error('每页条数必须是 1 到 100 之间的整数');
        pagination.value.size = 10;
    }
    // // 验证 requestType
    // if (filterParams.value.requestType && !['check_in', 'check_out'].includes(filterParams.value.requestType)) {
    //     ElMessage.error('无效的申请类型');
    //     filterParams.value.requestType = '';
    //     return;
    // }
    // // 验证 status
    // if (filterParams.value.status && !['pending', 'approved', 'rejected'].includes(filterParams.value.status)) {
    //     ElMessage.error('无效的状态');
    //     filterParams.value.status = '';
    //     return;
    // }
    pagination.value.page = 1;
    loadRequests();
};

// 重置筛选条件
const resetFilter = () => {
    filterParams.value = { requestType: '', status: '' };
    pagination.value.size = 10;
    pagination.value.page = 1;
    loadRequests();
};

// 页面初始化
onMounted(() => {
    loadRequests();
});
</script>

<template>
  <div class="check-in-out-page">
    <!-- 头部筛选区域 -->
    <el-card class="filter-card">
      <el-form :model="filterParams" inline>
        <el-form-item label="申请类型">
          <el-select v-model="filterParams.requestType" placeholder="请选择申请类型" clearable>
            <el-option
              v-for="item in requestTypeOptions2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="success" @click="openDialog">提交申请</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 申请列表 -->
    <el-card class="table-card">
      <el-table :data="requestList" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="申请ID" width="100" />
        <el-table-column prop="elderlyUserId" label="老人用户ID" width="150" />
        <el-table-column prop="requestType" label="申请类型" width="120">
          <template #default="{ row }">
            {{ row.requestType === 'CHECK_IN' ? '入住' : '退住' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="{
                PENDING: 'warning',
                APPROVED: 'success',
                REJECTED: 'danger'
            }[row.status]">
              {{ {
                PENDING: '待审核',
                APPROVED: '已通过',
                REJECTED: '已拒绝'
            }[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approvedByAdminId" label="审核管理员ID" width="150" />
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="申请时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'PENDING'"
              type="primary"
              size="small"
              @click="openReviewDialog(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.page"
        :page-size="pagination.size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="size => { pagination.size = size; handleFilter() }"
        class="pagination"
      />
    </el-card>

    <!-- 提交申请弹窗 -->
    <el-dialog title="提交入住/退住申请" v-model="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="老人用户ID" prop="elderlyUserId">
          <el-input v-model="form.elderlyUserId" placeholder="请输入老人用户ID" />
        </el-form-item>
        <el-form-item label="申请类型" prop="requestType">
          <el-select v-model="form.requestType" placeholder="请选择申请类型">
            <el-option
              v-for="item in requestTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>

    <!-- 审核申请弹窗 -->
    <el-dialog title="审核入住/退住申请" v-model="reviewDialogVisible" width="30%">
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef">
        <el-form-item label="审核管理员ID" prop="approvedByAdminId">
          <el-input v-model="reviewForm.approvedByAdminId" placeholder="请输入审核管理员ID" />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="reviewForm.status" placeholder="请选择审核状态">
            <el-option
              v-for="item in statusOptions2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="床位ID" prop="bedId" v-if="currentReviewRequestType === 'check_in' && reviewForm.status === 'APPROVED'">
          <el-input v-model="reviewForm.bedId" placeholder="请输入床位ID" />
        </el-form-item>
        <el-form-item label="审核备注" prop="notes">
          <el-input v-model="reviewForm.notes" type="textarea" placeholder="请输入审核备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleReviewSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.check-in-out-page {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;

  .filter-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #ffffff;
    padding: 20px;

    .el-form-item {
      margin-right: 20px;
      min-width: 200px; /* 确保筛选框有足够宽度 */
    }

    .el-select {
      width: 100%; /* 筛选框宽度占满 */
    }
  }

  .table-card {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #ffffff;
    padding: 20px;

    .el-table {
      border-radius: 8px;
      overflow: hidden;
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .el-button {
    border-radius: 6px;
    transition: all 0.3s;
    &:hover {
      transform: translateY(-2px);
    }
  }

  .el-dialog {
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  }
}
</style>